package com.zf.yichat.api.controller.goods;

import com.github.pagehelper.PageHelper;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.GoodsRedeemedRequest;
import com.zf.yichat.dto.IntegralDetailListDto;
import com.zf.yichat.dto.StGoodsDto;
import com.zf.yichat.dto.StGoodsRedeemedDto;
import com.zf.yichat.mapper.*;
import com.zf.yichat.model.*;
import com.zf.yichat.service.BalanceService;
import com.zf.yichat.service.GoodsService;
import com.zf.yichat.service.UserService;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.BalanceType;
import com.zf.yichat.vo.IntegralType;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.util.Contracts;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * 商品
 */
@RestController
@RequestMapping("goods")
@Slf4j
public class GoodsController extends BaseController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private BalanceService balanceService;

    @Autowired
    private UserService userService;

    @Resource
    private UserIntegralDetailMapper userIntegralDetailMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private StGoodsRedeemedMapper goodsRedeemedMapper;

    @Resource
    private StGoodsImgMapper goodsImgMapper;

    @Resource
    private UserBalanceMapper userBalanceMapper;
    /**
     * 查询商品列表
     * @return
     */
    @RequestMapping("/queryGoodsList")
    @ResponseBody
    public FsResponse queryGoodsList() {

        List<StGoodsDto> list = goodsService.queryGoodsList();
        for (StGoodsDto goods : list) {
            List<StGoodsImg> stGoodsImgs = goodsImgMapper.queryGoodsImgs(goods.getId());
            goods.setGoodsImgList(stGoodsImgs);
        }
       return FsResponseGen.successData(list);
    }



    /**
     * 兑换商品-消耗积分
     * @return
     */
    @RequestMapping("/redeemedGoods")
    @ResponseBody
    public FsResponse redeemedGoods(@RequestBody GoodsRedeemedRequest request) {

        try {
            Long userId = getUserId();
            // 查询用户的积分
            User user = userService.selectById(userId);
            if (null == user) {
                return FsResponseGen.failMsg("用户不存在：userId: " + userId);
            }

            // 根据商品的id查询商品，校验是否存在，价值多少积分
            Integer goodsId = request.getGoodsId();
            StGoods goods = goodsService.queryGoodsById(goodsId);
            if (null == goods) {
                return FsResponseGen.failMsg("商品无效：goodsId: " + goodsId);
            }

            // 更新用户积分，用户表的积分字段，用户积分表
            Integer integral = null == user.getIntegral() ? 0 : user.getIntegral();

            Integer points = null == goods.getPoints() ? 0 : goods.getPoints();

            if (points > integral) {
                return FsResponseGen.failMsg("您的积分不足，不能兑换该商品！");
            }

            // 校验支付密码
            String paymentPassword = request.getPaymentPassword();
            balanceService.checkPassword(userId, paymentPassword);


            updateIntegralDetail(IntegralType.MANGHE_CONSUME, goodsId.toString(),  (~(points - 1)), userId);

            // 新增兑换记录
            StGoodsRedeemed redeemed = new StGoodsRedeemed();
            redeemed.setGoodsId(goodsId);
            redeemed.setUserId(userId);
            redeemed.setCreateTime(new Date());
            goodsRedeemedMapper.insert(redeemed);


            return FsResponseGen.successMsg("商品兑换成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("兑换商品失败");
            return FsResponseGen.failMsg(e.getMessage());
        }
    }


    /**
     * 兑换商品-消耗余额
     * @return
     */
    @RequestMapping("/redeemedGoodsConsumptionBalance")
    @ResponseBody
    public FsResponse redeemedGoodsConsumptionBalance(@RequestBody GoodsRedeemedRequest request) {

        try {
            Long userId = getUserId();
            // 查询用户的余额
            UserBalance balance = userBalanceMapper.queryBalanceByUserId(userId);
            if (null == balance) {
                return FsResponseGen.failMsg("用户余额表不存在：userId: " + userId);
            }

            // 根据商品的id查询商品，校验是否存在，价值多少余额
            Integer goodsId = request.getGoodsId();
            StGoods goods = goodsService.queryGoodsById(goodsId);
            if (null == goods) {
                return FsResponseGen.failMsg("商品无效：goodsId: " + goodsId);
            }

            // 商品金额
            Integer points = null == goods.getPoints() ? 0 : goods.getPoints();
            BigDecimal amount = new BigDecimal(points);
            Contracts.assertTrue(balance.getIncomeBalance().compareTo(amount) >= 0, YiChatMsgCode.PACKET_CREATE_NO_ENOUGH_BALANCE.msg());

            // 校验支付密码
            String paymentPassword = request.getPaymentPassword();
            balanceService.checkPassword(userId, paymentPassword);

            // 更新用户余额
            balanceService.update(userId, BalanceType.USER_EXCHANGE_MALL_GOODS, amount, Long.valueOf(goodsId), "兑换商品");

            // 新增兑换记录
            StGoodsRedeemed redeemed = new StGoodsRedeemed();
            redeemed.setGoodsId(goodsId);
            redeemed.setUserId(userId);
            redeemed.setCreateTime(new Date());
            goodsRedeemedMapper.insert(redeemed);


            return FsResponseGen.successMsg("商品兑换成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("兑换商品失败");
            return FsResponseGen.failMsg(e.getMessage());
        }
    }

    /**
     * 更新用户积分
     * @param type
     * @param referId
     * @param score
     * @param userId
     */
    private void updateIntegralDetail(IntegralType type, String referId, Integer score, Long userId) {

        //增加用户积分记录-兑换商品
        UserIntegralDetail detail = new UserIntegralDetail();
        detail.setIntegral(score);
        detail.setReferType(type.getVal());
        detail.setMemo(type.getDesc());
        detail.setUserId(userId);
        detail.setReferId(referId);
        userIntegralDetailMapper.insertSelective(detail);

        //更新user表的积分值
        userMapper.addIntegral(score, userId);

    }

    /**
     * 查询已兑换的商品
     * @return
     */
    @RequestMapping("/queryRedeemedGoodsList")
    @ResponseBody
    public FsResponse queryRedeemedGoodsList(@RequestBody FsPage params) {

        try {
            Long userId = getUserId();
            PageHelper.startPage(params.getPageNo(), params.getPageSize());
            List<StGoodsRedeemedDto> list = goodsService.queryRedeemedGoodsList(userId);
            return DtoChangeUtils.getPageList(list, value -> {
                StGoodsRedeemedDto dto = new StGoodsRedeemedDto();
                BeanUtils.copyProperties(value, dto);
                return dto;
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取已兑换的商品失败");
        }

        return FsResponseGen.failMsg("获取已兑换的商品失败！");
    }



}
